package com.zb.response;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class VerificationCodeServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //生成验证码、去除缓存、3秒刷新
        BufferedImage image = new BufferedImage(150,30, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.WHITE);
        //填充颜色
        graphics.fillRect(0, 0, 180, 30);
        graphics.setColor(Color.ORANGE);
        graphics.setFont(new Font(null, Font.BOLD, 20));
        graphics.drawString(getCode(), 20, 20);

        resp.setHeader("refresh", "3");
        resp.setContentType("image/jpeg");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("expires", -1);
        resp.setHeader("Pragma", "no-cache");

        ImageIO.write(image, "jpg", resp.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    /**
     * 生成验证码
     */
    private String getCode(){
        Random random = new Random();
        String num = random.nextInt(9999999) + "";
        StringBuffer code = new StringBuffer();
        for (int i = 0; i < (7 -num.length()); i++){
            code.append("0");
        }

        return code + num;
    }
}
